package video;

import java.awt.BorderLayout;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JFrame;
import javax.swing.WindowConstants;

import org.gstreamer.elements.PlayBin;

/**
 * Class that creates the frame to show the video.
 * 
 * @version 0.3 December 01, 2009.
 * @author Heitor Meira de Melo.
 */
public class RunVideo implements Runnable {
	private final String STRING_VAZIA = "";
	private JFrame fullFrame = new JFrame("MarketingJoy");
	private TextOverlay textoverlay;

	/**
	 * Constructor of a RunVideo.
	 * 
	 * @param playbin
	 *            a VideoPlayer type to add to the Frame.
	 */
	public RunVideo(PlayBin playbin) {
		textoverlay = new TextOverlay();
		textoverlay.setSize(30); // Set the size of text.
		textoverlay.setYAlignment(100); // Set the alignment of the text.
		playbin.set("video-sink", textoverlay.getBin());
	}

	@Override
	public void run() {
		fullScreen();
	}

	/**
	 * Set the text to overlay the video.
	 * 
	 * @param text
	 *            The text to overlay the video.
	 */
	public void setText(String text) {
		if (text == null) {
			textoverlay.setText(STRING_VAZIA);
		} else {
			textoverlay.setText(text);
		}
	}

	/**
	 * Creates a full screen frame.
	 */
	private void fullScreen() {

		GraphicsEnvironment environment = GraphicsEnvironment
				.getLocalGraphicsEnvironment();
		GraphicsDevice device = environment.getDefaultScreenDevice();

		fullFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
		fullFrame.setUndecorated(true);
		fullFrame.setIgnoreRepaint(true);
		fullFrame.setResizable(false);
		fullFrame.add(textoverlay.getVideoComponent(), BorderLayout.CENTER);

		device.setFullScreenWindow(fullFrame);

		KeyListener keyListener = new KeyListener() {
			@Override
			public void keyPressed(KeyEvent keyEvent) {

				// This is a default operation, another key listeners can be
				// add.
				if (keyEvent.getKeyCode() == KeyEvent.VK_ESCAPE) {
					fullFrame.dispose();
				}
			}

			@Override
			public void keyReleased(KeyEvent arg0) {
				// TODO Auto-generated method stub

			}

			@Override
			public void keyTyped(KeyEvent arg0) {
				// TODO Auto-generated method stub

			}
		};

		fullFrame.addKeyListener(keyListener);
	}

	/**
	 * Add a KeyListener.
	 * 
	 * @param keylistener
	 *            The key listener to add.
	 */
	public void addKeyListener(KeyListener keylistener) {
		fullFrame.addKeyListener(keylistener);
	}
}
